package imageverificationcode

import (
	"fmt"
	"github.com/afocus/captcha"
	"image/color"
	"math/rand"
	"strconv"
)

var (
	BASE_ITEM           = []int{1, 2, 3, 4, 5, 6, 7, 8, 9} //基础数据项
	BASE_DIVISION_ITEM1 = []int{9, 8, 6, 4}                //为了不出现除不开的情况,只保留整数的除法关系
	BASE_DIVISION_ITEM2 = []int{3, 4, 3, 2}                //为了不出现除不开的情况,只保留整数的除法关系
	BASE_SYMBOL         = []string{"+", "-", "*", "/"}
)

const (
	REDIS_KEY_IMG_VERCODE = "ivc_" //图形验证码前缀
)

//创建图形验证码,返回验证码对应的答案
func CreateImgVerCode(width, height int) (*captcha.Image, string) {
	cap := captcha.New()
	err := cap.SetFont("comic.ttf")
	if err != nil {
		//logger.Error(err)
		return nil, ""
	}
	cap.SetSize(width, height)
	cap.SetBkgColor(color.White)
	cap.SetFrontColor(&color.NRGBA{
		uint8(rand.Intn(129)),
		uint8(rand.Intn(129)),
		uint8(rand.Intn(129)),
		0xFF,
	})
	str, answer := createRandVerCode()
	img := cap.CreateCustom(str)
	return img, answer
}

func createRandVerCode() (string, string) {
	f1 := BASE_ITEM[rand.Intn(len(BASE_ITEM))]
	f2 := BASE_ITEM[rand.Intn(len(BASE_ITEM))]
	sysbol := BASE_SYMBOL[rand.Intn(len(BASE_SYMBOL))]
	if sysbol == "/" { //为了不出现除不开的情况
		_i := rand.Intn(len(BASE_DIVISION_ITEM1))
		f1 = BASE_DIVISION_ITEM1[_i]
		f2 = BASE_DIVISION_ITEM2[_i]
	}
	result := 0
	randIndex := rand.Intn(3) //替换哪个数字为问号
	if sysbol == "+" {
		result = f1 + f2
	}
	if sysbol == "-" {
		result = f1 - f2
	}
	if sysbol == "*" {
		result = f1 * f2
	}
	if sysbol == "/" {
		result = f1 / f2
	}

	if randIndex == 0 {
		return fmt.Sprintf("? %s %d = %d", sysbol, f2, result), strconv.Itoa(f1)
	}
	if randIndex == 1 {
		return fmt.Sprintf("%d %s ? = %d", f1, sysbol, result), strconv.Itoa(f2)
	}
	if randIndex == 2 {
		return fmt.Sprintf("%d %s %d = ?", f1, sysbol, f2), strconv.Itoa(result)
	}
	return "", ""
}
